const r = require('koa-router')
const Router = new r()
const {dealUpload} = require('../utils/upload')
const {
  readBlog,
  getBlogList,
  register,
  valiateUser
} = require('../db/index')
// 登陆
Router
  .get('/', (ctx, next) => {
    ctx.session.login = true
    ctx.body = 'Hello'
  })
  .get('/verify', (ctx, next) => {
    ctx.body = 'LOGIN STATUS ' + ctx.session.login
  })
  .get('/login', async ctx => {
    return ctx.render('login')
  })

  .post('/login', async (ctx, next) => {
    let name = ctx.request.body.name || ''
    let password = ctx.request.body.password || ''
    const boo = await valiateUser(name, password)
    console.log('boo________', boo)
    if (boo) {
      ctx.cookies.set('LoginStatus', true, {
        expires: new Date(new Date().getTime() + 1000 * 60 * 30 )
      })

      ctx.body = ({
        code: 0,
        message: 'Success login'
      })

    } else {
      ctx.body = ({
        code: -100,
        message: 'failed login'
      })
    }
  })

  .post('/register', async (ctx, next) => {
    let name = ctx.request.body.name || ''
    let password = ctx.request.body.password || ''
    const boo = (await register(name, password))
    if (boo) {
      ctx.body = ({
        code: 0,
        message: 'Success register'
      })
    } else {
      ctx.body = ({
        code: -100,
        message: 'failed register'
      })
    }
  })


  // 上传文件
  .get('/upload', ctx => {
    return ctx.render('upload')
  })
  .post('/upload', ctx => {
    dealUpload(ctx).then(() => ctx.body = 'uploadSuccess!!!')
  })

  // 删除某篇博客
  .post('/delete/blog/:blogId', async (ctx, next) => {

  })

  // 修改博客的分类
  .post('/modify/blog/:blogId/:kindName', async (ctx, next) => {

  })

  // 查看某一篇博客
  .get('/blog/:blogId', async (ctx, next) => {
    let blogId = ctx.params.blogId
    let content = await readBlog(blogId)
    return ctx.render('detail', {
      result: content.content
    })
    await next()
  })

  // 查看博客列表
  .get('/blogList', async (ctx, next) => {
    console.log('blogList in')
    const result = await getBlogList('/')
    ctx.response.type = 'text/html; charset=utf-8'

    const body = ctx.render('index', {
      result
    })
    await next()
    return body
  })

module.exports = Router